import moment from 'moment';
import {
    ElMessage
} from 'element-plus'
import './lib/jszip' //多文件压缩插件

// 获取有时效的sessionStorage
export function getLocalStorage(key) {
    let item = localStorage.getItem(key);
    // 先将拿到的试着进行json转为对象的形式
    try {
        item = JSON.parse(item);
    } catch (error) {
        // eslint-disable-next-line no-self-assign
        item = item;
    }
    // 如果有startTime的值，说明设置了失效时间
    if (item && item.startTime) {
        let date = new Date().getTime();
        // 如果大于就是过期了，如果小于或等于就还没过期
        if (date - item.startTime > item.expires) {
            localStorage.removeItem(key);
            return '';
        } else {
            return item.value;
        }
    } else {
        return item;
    }
}

export function setLocalStorage(key, value, expires) {
    let params = {
        key: key,
        value: value,
        expires: expires
    };
    if (expires) {
        // 记录何时将值存入缓存，毫秒级
        let data = Object.assign(params, {
            startTime: new Date().getTime()
        });
        localStorage.setItem(key, JSON.stringify(data));
    } else {
        if (Object.prototype.toString.call(value) == '[object Object]') {
            value = JSON.stringify(value);
        }
        if (Object.prototype.toString.call(value) == '[object Array]') {
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
    }
}

/**
 * 获取本月当天之前日期集合(yyyy-MM-dd)
 */
export function currentMonthDays() {
    // 获取标准时间
    const date = new Date();
    // 获取当天日期
    const currentDay = date.getDate();
    // 获取当前月份（实际月份需要加1）
    const currentMonth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    // 获取当前年份
    const currentYear = date.getFullYear();
    // 获取当前月有多少天
    const currentMonthDays = new Date(currentYear, currentMonth, 0).getDate();
    // 当前月份所有日期集合
    const currentMonthArr = [];
    for (let day = 1; day <= currentMonthDays; day++) {
        // 截至当前日期为止
        if (day <= currentDay) {
            // 年月日(yyyy-MM-dd)
            let dateItem = currentYear + "-" + currentMonth + "-" + (day < 10 ? '0' + day : day)
            currentMonthArr.push(dateItem)
        }
    }
    return currentMonthArr.reverse();
}

export function currentWeek() {
    let endTime = moment().format("YYYY-MM-DD");
    let startTime = moment().subtract(6, 'days').format("YYYY-MM-DD");
    let dateList = [];
    for (let i = 6; i >= 1; i--) {
        dateList.push(moment().subtract(i, 'days').format("YYYY-MM-DD"));
    }
    dateList.push(endTime);
    return {
        startTime,
        endTime,
        dateList
    }
}

/**
 * 时间排序算法
 */
export function sortDate(property, bol) { //property是你需要排序传入的key,bol为true时是升序，false为降序
    return function (a, b) {
        var value1 = a[property];
        var value2 = b[property];
        if (bol) {
            // 升序
            return Date.parse(value1) - Date.parse(value2);
        } else {
            // 降序
            return Date.parse(value2) - Date.parse(value1)
        }
    }
}

/**
 * 时间格式化
 */
export function formatDate(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);

    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    const hours = ("0" + date.getHours()).slice(-2);
    const minutes = ("0" + date.getMinutes()).slice(-2);
    const seconds = ("0" + date.getSeconds()).slice(-2);

    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    console.log(formattedDate); // 输出: 2023-03-10 08:00:00
    return formattedDate
}


// 下载各类型文件
export class FileDownLoad {
    constructor(path, process) {
        if (Array.isArray(path)) {
            if (path.length > 1) {
                this.isMult = true
                this.path = path
            } else {
                this.path = path[0]
                this.isMult = false
            }
        } else {
            this.path = path;
            this.isMult = false
        }

        this.controller = new AbortController();
        this.getProcess = process
    }

    //下载文件
    downloadPaper() {
        if (this.isMult) {
            this.downloadMult()
        } else {
            this.downloadSingle()
        }
    }

    //多文件压缩zip后下载 需引入多文件压缩插件
    async downloadMult() {
        const zip = new JSZip();
        const {
            signal
        } = this.controller;
        for (let i = 0; i < this.path.length; i++) {
            // 获取文件名称
            let fileName = this.getFileName(this.path[i]);
            let fileType = this.getFileType(this.path[i]);
            try {
                const response = await fetch(this.path[i], {
                    method: "get",
                    mode: "cors",
                    signal
                })

                //设置下载进度
                const data = await this.setProcess(response, fileName);

                zip.file(fileName, new Blob(data, {
                    type: fileType == "pdf" ? "application/pdf" : fileType == "word" ?
                        "application/msword" : fileType == "excel" ? "application/vnd.ms-excel" : ""
                }));
            } catch (error) {
                //是否是用户中止下载操作
                if (error.name === 'AbortError') {
                    ElMessage({
                        showClose: true,
                        message: '中止下载',
                        type: 'error',
                    })
                } else {
                    ElMessage({
                        showClose: true,
                        message: '下载出错了',
                        type: 'error',
                    })
                }
            }
        }

        zip.generateAsync({
            type: "blob"
        }).then((content) => {
            let url = window.URL.createObjectURL(content);

            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", this.getFileName(this.path[0]) + '等文件.zip');
            document.body.appendChild(link);
            link.click();
            link.remove();
        });
    }



    //单个文件下载
    downloadSingle() {
        // 获取文件类型
        let type = this.getFileType(this.path);
        // 获取文件名称
        let fileName = this.getFileName(this.path);
        if (type == 'img') {
            this.downloadImg(this.path).then((res) => {
                // 创建标签
                const link = document.createElement("a");
                link.href = res;
                // a 标签设置 download 属性，直接下载图片
                link.setAttribute("download", fileName + '.png');
                document.body.appendChild(link);
                link.click();
                link.remove();
            }).catch((err) => {
                console.log(err);
            })
        } else {
            this.downloadFile({
                url: this.path,
                type: type,
                name: fileName
            })
        }
    }
    getFileType(url) {
        if (url) {
            // 先用斜杠截取
            let tempArr1 = url.split('/');
            // 获取到截取结果的最后一位，即文件名称
            let fileName = tempArr1[tempArr1.length - 1];
            // 再用点截取
            let tempArr2 = fileName.split('.');
            // 得到文件类型
            let type = tempArr2.at(-1);
            let myType = ''
            if (type == 'jpg' || type == 'jpeg' || type == 'png') {
                myType = 'img'
            } else if (type == 'pdf') {
                myType = 'pdf'
            } else if (type == 'doc' || type == 'doxc') {
                myType = 'word'
            } else if (type == 'xlsx' || type == 'xls') {
                myType = 'excel'
            }
            return myType;
        } else {
            return '';
        }
    }
    getFileName(url) {
        if (url) {
            // 先用斜杠截取
            let tempArr1 = url.split('/');
            // 获取到截取结果的最后一位，即文件名称
            let fileName = tempArr1[tempArr1.length - 1];
            return fileName;
        } else {
            return '';
        }
    }
    downloadImg(url) {
        return new Promise((resolve, reject) => {
            // 重绘图片
            let image = new Image();
            image.onload = function () {
                let canvas = document.createElement('canvas');
                canvas.width = this.naturalWidth;
                canvas.height = this.naturalHeight;
                canvas.getContext('2d').drawImage(image, 0, 0);
                let result = canvas.toDataURL('image/png')
                resolve(result);
            };
            // 跨域获取当前图片
            image.setAttribute("crossOrigin", 'Anonymous');
            image.src = url
            image.onerror = () => {
                reject(new Error('urlToBase64 error'));
            };
        })
    }

    setProcess(response, name) {
        try {
            return new Promise(async resolve => {
                const reader = response.body.getReader();
                const contentLength = +response.headers.get('Content-Length');
                let receiveLength = 0;
                let chunks = [];
                while (true) {
                    const {
                        done,
                        value
                    } = await reader.read();
                    if (done) {
                        break
                    }
                    chunks.push(value);
                    receiveLength += value.length;
                    this.getProcess(receiveLength, contentLength, name)
                }
                resolve(chunks)
            })
        } catch (error) {
            if (error.name === 'AbortError') {
                ElMessage({
                    showClose: true,
                    message: '中止下载',
                    type: 'error',
                })
            } else {
                ElMessage({
                    showClose: true,
                    message: '下载出错了',
                    type: 'error',
                })
            }
        }

    }
    downloadFile(data) {
        const {
            signal
        } = this.controller;
        try {
            fetch(data.url, {
                method: "get",
                mode: "cors",
                signal
            })
                .then((response) => {
                    //下载进度设置
                    this.setProcess(response, data.name).then((res) => {
                        const downloadUrl = window.URL.createObjectURL(
                            //new Blob() 对后端返回文件流类型处理
                            new Blob(res, {
                                type: data.type == "pdf" ? "application/pdf" : data.type == "word" ?
                                    "application/msword" : data.type == "excel" ? "application/vnd.ms-excel" : ""
                            })
                        );
                        //word文档为msword,pdf文档为pdf
                        const link = document.createElement("a");
                        link.href = downloadUrl;
                        link.setAttribute("download", data.name);
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                    })
                })

        } catch (error) {
            if (error.name === 'AbortError') {
                ElMessage({
                    showClose: true,
                    message: '中止下载',
                    type: 'error',
                })
            } else {
                ElMessage({
                    showClose: true,
                    message: '下载出错了',
                    type: 'error',
                })
            }
        }

    }
}


//车牌格式正则表达式（含新能源）
export const lprFormat = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;

/**
 * 时间格式化
 * 2023-03-01T13:00:00.000Z
 */
export function transformTZToLocal(tzStr) {
    let time = new Date(tzStr).getTime();
    let date = new Date(time);
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    const hours = ("0" + date.getHours()).slice(-2);
    const minutes = ("0" + date.getMinutes()).slice(-2);
    const seconds = ("0" + date.getSeconds()).slice(-2);

    const formattedDate = `${year}.${month}.${day}`;
    console.log(formattedDate); // 输出: 2023-03-10 08:00:00
    return formattedDate
}

//文字溢出判断
export function isEllipsis(e) {
    return new Promise(resolve => {
        const el = window.event || e; // 浏览器兼容，最好写一下
        const eles = el.target;
        const elComputed = document.defaultView.getComputedStyle(eles, '');
        const padding =
            parseInt(elComputed.paddingLeft.replace('px', '')) + parseInt(elComputed.paddingRight.replace('px', ''));

        const range = document.createRange();
        range.setStart(eles, 0);
        range.setEnd(eles, eles.childNodes.length);
        const rangeWidth = range.getBoundingClientRect().width;
        if (rangeWidth + padding > eles.offsetWidth || eles.scrollWidth > eles.offsetWidth) {
            resolve(true);
        } else {
            resolve(false);
        }
    });
}

//身份证脱敏
export function cardHide(card = "") {
    const reg = /^(.{4})(?:\d+)(.{4})$/; // 匹配身份证号前4位和后4位的正则表达式
    const maskedIdCard = card.replace(reg, '$1**********$2'); // 身份证号脱敏，将中间替换为“*”
    return maskedIdCard; 
}